<script setup>
import Aliplayer from 'aliyun-aliplayer';
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css';
import { getCameraListApi } from '@/apis/user'
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useIndexStore } from '@/stores/index'
import { closeDialog, showDialog, showToast } from 'vant';
const indexStore = useIndexStore()

const route = useRoute()
const router = useRouter()

// 当前是否是pc端
const IsPC = () => {
    var userAgentInfo = navigator.userAgent;
    var Agents = new Array(
        "Android",
        "iPhone",
        "SymbianOS",
        "Windows Phone",
        "iPad",
        "iPod"
    );
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

const ispc = indexStore.ispc = IsPC()

let { id, stream_id } = route.query

let cid = ref(id), ctitle = ref(''), curl = ref(''), streamid = ref(stream_id)
// 获取token
const token = localStorage.getItem('token')
// let uuid = ref('')
// let isopen = ref(false) // 是否成功拉取直播流

// // 获取页面凭证
// const getCameraToken = async () => {
//     uuid.value = ''
//     let res = await getCameraTokenApi({ token })
//     if (res.data.code == 200) {
//         uuid.value = res.data.data.uuid
//     } else {
//         showToast(res.data.msg)
//     }
// }

// 当前权限列表
let cameraList = reactive([])

// 其他区域摄像机列表
// let otherlist = reactive([])

// let timer = ref(null)
// // 检测监控链接是否过期
// const checkCameraUrlIsValid = (dateat) => {
//     let now = parseInt(new Date().getTime() / 1000)
//     if (now > Number(dateat)) {
//         // 过期
//         showDialog({
//             message: '监控链接已过期，请刷新页面重新获取',
//             theme: 'round-button',
//         }).then(() => {
//             // on close
//             // otherlist = []
//             getCameraList()
//         });
//         clearInterval(timer.value)
//     }
// }

// 查询当前用户数据权限列表
const getCameraList = async () => {
    const res = await getCameraListApi({ token })
    // console.log(res)
    if (res.data.code === 200) {
        cameraList = res.data.data.streams
        cameraList.forEach(item => {
            if (item.tag === cid.value) {
                ctitle.value = item.push_name
                curl.value = item.player_m3u8_url
                // 监控过期时间
                // let cameraUrlDateTo = item.expire_at
                // timer.value = setInterval(() => {
                //     checkCameraUrlIsValid(cameraUrlDateTo)
                // }, 60 * 1000)
            } else {
                // otherlist.push(item)
            }
        })
    } else {
        showToast(res.data.msg)
    }
}

if (token) {
    // getCameraToken()
    getCameraList()
} else {
    showToast('请先登录')
    router.replace('/cn')
}


let player = ref(null)
let isloading = ref(false) //是否加载中

// 创建播放器
let createPlayer = (url) => {
    player.value = new Aliplayer({
        id: 'playerCont',
        width: "100%",
        height: "100%",
        autoplay: true,
        language: "en-us",
        source: url,
        isLive: true,
        useH5Prism: true, //启用H5播放器
        playsinline: true,
        preload: true,
        // mute: true, //静音
        controlBarVisibility: "always",
        skinLayout: [
            {
                name: "bigPlayButton",
                align: "blabs",
                x: 30,
                y: 80
            },
            {
                name: "errorDisplay",
                align: "tlabs",
                x: 0,
                y: 0
            },
            {
                name: "infoDisplay"
            },
            {
                name: "controlBar",
                align: "blabs",
                x: 0,
                y: 0,
                children: [
                    {
                        name: "liveDisplay",
                        align: "tlabs",
                        x: 15,
                        y: 0
                    },
                    {
                        name: "fullScreenButton",
                        align: "tr",
                        x: 60,
                        y: 0
                    },
                    // {
                    //     name: "volume",
                    //     align: "tr",
                    //     x: 5,
                    //     y: 10
                    // }
                ]
            }
        ]
    });

    // 数据缓冲事件
    player.value.on('waiting', () => {
        console.log('缓冲中');
        isloading.value = true
    })
    // 数据加载完成事件
    player.value.on('canplay', () => {
        console.log('可以播放');
        isloading.value = false
    })
    // 错误事件
    player.value.on('error', () => {
        console.log('错误');
        isloading.value = false
    })
}
let time = ref(10 * 60) //10分钟
let intervalId = ref(null)
let waitTime = ref(time.value)

const initCountdown = () => {
    if (intervalId.value) {
        clearInterval(intervalId.value);
    }
    intervalId.value = setInterval(handleCountdown, 1000);
    const body = document.querySelector('#live');
    body.addEventListener("click", resetCountdown);
    body.addEventListener("keydown", resetCountdown);
    body.addEventListener("mousemove", resetCountdown);
    body.addEventListener("mousewheel", resetCountdown);
}

const handleCountdown = () => {
    waitTime.value--
    // 倒计时结束
    if (waitTime.value <= 0) {
        doInspection();
        if (intervalId.value) {
            clearInterval(intervalId.value);
        }
    }
}

const doInspection = () => {
    let openin = ref(0)
    let showtimer = ref(null)
    showDialog({
        message: '现场直播链接已过期，请刷新页面并重新获取',
        theme: 'round-button',
    }).then(() => {
        // on close
        openin.value = 1
        clearTimeout(showtimer.value)
        // 重置
        resetCountdown()
    });
    if (openin.value === 0) {
        // 弹窗后10分钟未关闭则回到上一页
        showtimer.value = setTimeout(() => {
            clearTimeout(showtimer.value)
            clearInterval(intervalId.value);
            router.replace('/cn/map_local')
            closeDialog()
        }, 10 * 60 * 1000)
    }
}

// 重置倒计时
const resetCountdown = () => {
    waitTime = ref(time.value)
    if (intervalId.value) {
        clearInterval(intervalId.value);
    }
    intervalId.value = setInterval(handleCountdown, 1000);
}

onMounted(() => {
    // 页面检测 进入页面10分钟后，出提示，提示后10分钟未关闭则回到上一页
    initCountdown()
})

// // 开启直播
// let openLive = async () => {
//     isopen.value = false
//     isloading.value = true
//     let res = await startLiveApi({ token, uuid: uuid.value, stream_id: streamid.value })
//     if (res.data.code == 200) {
//         isopen.value = true
//         createPlayer(curl.value)
//     }
// }

// // 离开页面后请求后台关闭直播
// let closeLive = async () => {
//     await stopLiveApi({ token, uuid: uuid.value, stream_id: streamid.value })
// }

// 切换摄像头
const changeCamera = (id, name, url, steamid) => {
    ctitle.value = name
    curl.value = url
    streamid.value = steamid
    isplay.value = false
    // 关闭当前直播
    // closeLive()
    // 获取页面凭证
    // getCameraToken()
    // 拉取直播流
    // if (uuid.value) {
    //     openLive()
    // }
    // 更新其他列表
    // otherlist = []
    // cameraList.forEach(item => {
    //     if (item.tag !== id) {
    //         otherlist.push(item)
    //     }
    // })
}

onUnmounted(() => {
    clearInterval(intervalId.value);
})

// 返回
const goback = () => {
    router.replace('/cn/map_local')
    clearInterval(intervalId.value);
    // closeLive()
}

let isplay = ref(false) //是否播放
// 点击播放
const playvideo = () => {
    // console.log(curl.value);
    if (curl.value) {
        isplay.value = true
    }
    if (player.value) {
        player.value.dispose()
    }
    // 请求后台拉取直播流
    // openLive()
    createPlayer(curl.value)
}

</script>

<template>
    <div class="live box bg3 clmcenter" id="live">
        <div class="controlbox">
            <img src="@/assets/img/back.png" class="btn_goback" @click="goback">
            <img src="@/assets/img/menu.png" class="btn_menu" @click="$router.replace('/cn/main')" />
        </div>
        <img src="@/assets/img/logo.png" class="logo" alt="logo">
        <div class="container clmstart">
            <div class="stitle">
                <img src="@/assets/img/title_left.png" class="title_left anileft" />
                <p>现场参观</p>
                <img src="@/assets/img/title_right.png" class="title_right aniright" />
            </div>
            <!-- 一个机位 -->
            <div class="camerabox onepointbox clmstart" :style="{ marginTop: ispc ? '' : '1.5vw' }">
                <div class="livevideobox clmcenter">
                    <img src="@/assets/img/live1.png" class="liveposter" v-show="!isplay" />
                    <img src="@/assets/img/livebox.png" class="livewrapper" />
                    <img src="@/assets/img/btn_play.png" class="playbtn" v-show="!isplay" @click="playvideo" />
                    <div class="camerasource" id="playerCont"></div>
                    <van-loading color="#00B9A2" style="z-index: 9;" text-color="#ffffff" vertical
                        v-show="isloading">loading</van-loading>
                </div>
                <div class="livetitle" :style="{ marginTop: ispc ? '' : '1vw' }">
                    <img src="@/assets/img/border-left.png" class="border_left" />
                    <p>{{ ctitle.replace('摄像机', '') }}</p>
                    <img src="@/assets/img/border-right.png" class="border_right" />
                </div>
            </div>
            <!-- 底部按钮区 -->
            <div class="otherareabox" :style="{ marginTop: ispc ? '' : '1vw' }">
                <button type="button" class="btn" v-for="item in cameraList" :key="item.tag"
                    @click="changeCamera(item.tag, item.push_name, item.player_m3u8_url, item.stream_id)">{{
                        item.push_name.replace('摄像机', '') }}</button>
            </div>
            <!-- 两个机位 -->
            <!-- <div class="camerabox twopointbox" v-show="!oneflag" :style="{ marginTop: ispc ? '' : '4vw' }">
                <div class="camerainfobox clmstart">
                    <div class="livevideobox clmcenter">
                        <img src="@/assets/img/live2.png" class="liveposter" />
                        <img src="@/assets/img/livebox.png" class="livewrapper" />
                        <img src="@/assets/img/btn_play.png" class="playbtn" />
                        <div class="camerasource" ref="point2_1"></div>
                    </div>
                    <div class="livetitle">
                        <img src="@/assets/img/border-left.png" class="border_left" />
                        <p>左摄像机</p>
                        <img src="@/assets/img/border-right.png" class="border_right" />
                    </div>
                </div>
                <div class="areatitle">{{ title }}</div>
                <div class="camerainfobox clmstart">
                    <div class="livevideobox clmcenter">
                        <img src="@/assets/img/live3.png" class="liveposter" />
                        <img src="@/assets/img/livebox.png" class="livewrapper" />
                        <img src="@/assets/img/btn_play.png" class="playbtn" />
                        <div class="camerasource" ref="point2_2"></div>
                    </div>
                    <div class="livetitle">
                        <img src="@/assets/img/border-left.png" class="border_left" />
                        <p>右摄像机</p>
                        <img src="@/assets/img/border-right.png" class="border_right" />
                    </div>
                </div>
            </div> -->
        </div>
    </div>
</template>
<style>
.van-dialog__message {
    padding: 2vw !important;
}
</style>
<style lang="scss" scoped>
.live {
    overflow: hidden scroll;
    .container {
        position: relative;
        width: 100%;
        .camerabox {
            .livetitle {
                display: flex;
                justify-content: center;
                align-items: center;
                p {
                    font-size: 1.25vw;
                    color: #ffffff;
                    padding-bottom: 0.3vw;
                }
                .border_left {
                    width: 0.677vw;
                    height: 1.979vw;
                    margin-right: 0.36vw;
                }
                .border_right {
                    width: 1.51vw;
                    height: 1.979vw;
                    margin-left: -0.52vw;
                }
            }
        }
        .onepointbox,
        .twopointbox {
            .livevideobox {
                position: relative;
                filter: drop-shadow(0.2vw 0.65vw 0.4vw rgba(0, 0, 0, 0.3));
                .liveposter {
                    position: relative;
                    z-index: 2;
                    width: 100%;
                    height: 100%;
                    pointer-events: none;
                }
                .livewrapper {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    z-index: 2;
                    pointer-events: none;
                }
                .playbtn {
                    position: absolute;
                    z-index: 3;
                    width: 4.9vw;
                    cursor: pointer;
                }
                .camerasource {
                    position: absolute;
                    z-index: 1;
                    top: 0;
                    left: 0;
                    background-color: #000;
                    overflow: hidden;
                }
            }
        }
        .onepointbox {
            margin-top: 3.385vw;
            .livevideobox {
                width: 48.07vw;
                height: 27.14vw;
                .camerasource {
                    width: 48.07vw;
                    height: 27.14vw;
                    clip-path: polygon(3.542vw 0, 100% 0, 100% calc(100% - 3.542vw), calc(100% - 3.542vw) 100%, 0 100%, 0 3.542vw, 3.542vw 0);
                }
            }
            .livetitle {
                margin-top: 1.82vw;
            }
        }
        .otherareabox {
            width: 100vw;
            margin-top: 3.49vw;
            display: flex;
            justify-content: center;
            align-items: center;
            button {
                width: 9vw;
                height: 2.24vw;
                font-size: 1.057vw;
                margin: 0 0.3vw;
            }
        }
        .twopointbox {
            margin-top: 5.9375vw;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            .camerainfobox {
                .livevideobox {
                    width: 35.1vw;
                    height: 19.79vw;
                    .camerasource {
                        width: 35.1vw;
                        height: 19.79vw;
                        clip-path: polygon(2.29vw 0, 100% 0, 100% calc(100% - 2.29vw), calc(100% - 2.29vw) 100%, 0 100%, 0 2.29vw, 2.29vw 0);
                    }
                }
                .livetitle {
                    margin-top: 1.67vw;
                }
            }
            .areatitle {
                margin: 7.55vw 1.6vw 0 2vw;
                font-size: 1.7vw;
                color: #ffffff;
                letter-spacing: 0.7vw;
                text-align: center;
                line-height: 1.3;
            }
        }
    }
}
</style>